// Copyright (C) 2015, Alberto Corona <alberto@0x1a.us>
// All rights reserved. This file is part of core-utils, distributed under the
// GPL v3 license. For full terms please see the LICENSE file.

#![crate_type = "bin"]
#![crate_name = "mv"]
#![feature(collections)]

static VERS: &'static str = "0.1.0";
static PROG: &'static str = "mv";

extern crate getopts;
extern crate util;

use getopts::{Options};
use util::{Status};

use std::env;
use std::fs;
use std::path::{PathBuf};

fn rename(from: PathBuf, to: PathBuf) {
    match fs::rename(from, to) {
        Ok(s) => { s },
        Err(e) => {
            util::err(PROG, Status::Error, e.to_string());
        }
    }
}

fn print_usage(prog: &str, opts: Options) {
    let brief = format!("Usage: {} [OPTION] SOURCE DEST\nRename SOURCE to DEST", prog);
    print!("{}", opts.usage(&brief));
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let mut opts = Options::new();

    opts.optflag("h", "help", "Print the help menu");
    opts.optflag("", "version", "Print the version of mv");

    let matches = match opts.parse(&args[1..]) {
        Ok(m) => { m },
        Err(e) => {
            util::err(PROG, Status::OptError, e.to_string());
            panic!(e.to_string())
        }
    };

    if matches.opt_present("h") {
        print_usage(PROG, opts);
    } else if matches.opt_present("version") {
        util::copyright(PROG, VERS, "2015", vec!["Alberto Corona"]);
    } else {
        match matches.free.first() {
            Some(src) => {
                if matches.free.len() == 1 {
                    println!("mv: No destination specified for '{}'", src);
                    util::exit(Status::Error);
                }
                for items in matches.free.tail() {
                    rename(PathBuf::from(src), PathBuf::from(items));
                }
            }
            None => {
                println!("mv: No files specified");
                util::exit(Status::Error);
            }
        };
    }
}
